package com.androsz.ramdroidx;

import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.KeyEvent;

public class SettingsActivity extends PreferenceActivity {

	int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

	private void initializePrefs() {

		final SharedPreferences userPrefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		final int updateFrequency = userPrefs.getInt(
				getString(R.string.prefs_key_update_frequency), -1);
		final String updateMethod = userPrefs.getString(getString(R.string.prefs_key_update_method), "");

		if (updateFrequency < 0 || updateMethod.length() == 0) {
			final SharedPreferences.Editor ed = userPrefs.edit();
			ed.putInt(getString(R.string.prefs_key_update_frequency), 1);
			ed.putString(getString(R.string.prefs_key_update_method), "Toggle");
			ed.commit();
		}
	}

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		stopService(new Intent(this, UpdateWidgetService.class));
		initializePrefs();
		addPreferencesFromResource(R.xml.settings);

		final Intent intent = getIntent();
		final Bundle extras = intent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		final Intent resultValue = new Intent();
		resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
		setResult(RESULT_OK, resultValue);
	}

	@Override
	protected void onDestroy() {

		final SharedPreferences userPrefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		final String updateMethod = userPrefs.getString(getString(R.string.prefs_key_update_method), "");

		if (updateMethod.equals("Continuous")) {
			startService(new Intent(RAMDroidWidget.ACTION_START_UPDATE_RAM, null, this, UpdateWidgetService.class));
		} else {
			startService(new Intent(RAMDroidWidget.ACTION_READY_TAP, null, this, UpdateWidgetService.class));
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyUp(final int keyCode, final KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
			final Intent resultValue = new Intent();
			resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
			setResult(RESULT_OK, resultValue);
			finish();
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onPause() {
		finish();
		super.onPause();
	}
}